package com.kyxx.topics.activity;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.TestAdapter;
import com.kyxx.topics.bean.ArticleDetailBean;
import com.kyxx.topics.bean.CommentBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.CommonUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.SettingUtils;
import com.kyxx.topics.utils.StatusBarCompat;
import com.kyxx.topics.utils.TimeUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.ListViewForScrollView;
import com.kyxx.topics.widget.ObservableListView;
import com.kyxx.topics.widget.PtrClassicFrameLayout2;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.Header;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.Call;
import okhttp3.Response;

public class DetailActivity extends BaseActivity implements View.OnClickListener {
    private boolean isshow = true;
    float y1 = 0;
    float y2 = 0;
    private LinearLayout ll_bottom;
    private Drawable bgTopBarDrawable;
    private PtrClassicFrameLayout2 ptrv;
    private static final float ALPHAMAX = 255.0f;
    private int alpha = 0;
    private ObservableListView lvfs;
    private TextView tv_write_value;
    private RelativeLayout rl_value;
    private TextView tv_value_num;
    private LinearLayout ll_focus;
    private LinearLayout ll_share;
    private AlertDialog alertDialog;
    private EditText dialog_et_content;
    private TextView dialog_tv_title;
    private TextView btn_submit;
    private View topView;
    private WebView wv;
    private RelativeLayout rl_progress;
    private ProgressBar avi;
    private LinearLayout ll_reload;
    private int pageSize = 1;
    private int countSize = 20;
    ValueAdapter valueAdapter = new ValueAdapter();
    private int lastVisiblePosition;
    private ArticleDetailBean articleDetailBean;
    private List<CommentBean> commentBeanList = new ArrayList<>();
    private PopupWindow popupWindow;
    private View layout;
    private int mark;
    private ImageView iv_focus;
    private int position;
    private CommentBean parentCommentBean;
    private SettingUtils settingUtils = new SettingUtils();
    protected DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisk(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnFail(R.mipmap.icon_user_default)
            .showImageOnLoading(R.mipmap.icon_user_default)
            .showImageForEmptyUri(R.mipmap.icon_user_default)
            .build();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    rl_progress.setVisibility(View.GONE);
                    valueAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    rl_progress.setVisibility(View.VISIBLE);
                    avi.setVisibility(View.GONE);
                    ll_reload.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_detail);
        StatusBarCompat.compat(this, 0xffffffff);
    }

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(Html.fromHtml(title).toString());
        top_bar.setVisibility(View.GONE);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.GONE);
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_tv_right.setText("查看专题");
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        top_bar_iv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startActivity(new Intent(context, ZhuanTiActivity.class));
//                popupWindow.showAtLocation(ptrv, Gravity.TOP | Gravity.RIGHT, 0, 0);
                popupWindow.showAsDropDown(top_bar_iv_right);
            }
        });
    }

    @Override
    protected void findViewById() {
        initPopupWindow();
        loadTopBar(getIntent().getStringExtra("title"));
        ll_bottom = (LinearLayout) findViewById(R.id.ll_bottom);
        ptrv = (PtrClassicFrameLayout2) findViewById(R.id.ptrv);
        lvfs = (ObservableListView) findViewById(R.id.lvfs);
        tv_write_value = (TextView) findViewById(R.id.tv_write_value);
        rl_value = (RelativeLayout) findViewById(R.id.rl_value);
        tv_value_num = (TextView) findViewById(R.id.tv_value_num);
        ll_focus = (LinearLayout) findViewById(R.id.ll_focus);
        ll_share = (LinearLayout) findViewById(R.id.ll_share);
        rl_progress = (RelativeLayout) findViewById(R.id.rl_progress);
        avi = (ProgressBar) findViewById(R.id.avi);
        ll_reload = (LinearLayout) findViewById(R.id.ll_reload);
        ll_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDetail();
                initComment(Constants.INITDATA);
            }
        });
        iv_focus = (ImageView) findViewById(R.id.iv_focus);
        initHeader();
    }

    @Override
    protected void setListener() {
        tv_write_value.setOnClickListener(this);
        rl_value.setOnClickListener(this);
        ll_focus.setOnClickListener(this);
        ll_share.setOnClickListener(this);
        ptrv.setMode(PtrFrameLayout.Mode.NONE);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        ptrv.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(final PtrFrameLayout frame) {
                startActivity(new Intent(DetailActivity.this, DetailActivity.class));
                finish();
                overridePendingTransition(R.anim.in_from_bottom, R.anim.out_from_top);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                startActivity(new Intent(DetailActivity.this, DetailActivity.class));
                finish();
                overridePendingTransition(R.anim.in_from_top, R.anim.out_from_bottom);
            }
        });

//        sv.setScrollViewListener(new ScrollViewListener() {
//            @Override
//            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
//                alpha = (int) (y * ALPHAMAX / SizeUtils.dp2px(context, 180));
//                System.out.println(alpha);
//                if (alpha > ALPHAMAX) {
//                    alpha = (int) ALPHAMAX;
//                }
//                bgTopBarDrawable = top_bar.getBackground();
//                bgTopBarDrawable.mutate().setAlpha(alpha);
//                top_bar_tv_title.setTextColor(Color.argb(alpha, 255, 255, 255));   //文字透明度
//            }
//        });

//        lvfs.setScrollViewListener(new ListViewListener() {
//            @Override
//            public void onScrollChanged(ObservableListView scrollView, int x, int y, int oldx, int oldy) {
//                alpha = (int) (Math.abs(topView.getTop()) * ALPHAMAX / SizeUtils.dp2px(context, 180));
//                System.out.println(alpha);
//                if (alpha > ALPHAMAX) {
//                    alpha = (int) ALPHAMAX;
//                }
//                bgTopBarDrawable = top_bar.getBackground();
//                bgTopBarDrawable.mutate().setAlpha(alpha);
//                top_bar_tv_title.setTextColor(Color.argb(alpha, 255, 255, 255));   //文字透明度
//            }
//        });
        lvfs.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (lastVisiblePosition == lvfs.getLastVisiblePosition())
                    return;
                lastVisiblePosition = lvfs.getLastVisiblePosition();
                Log.e("topic", lastVisiblePosition + "onScroll" + lvfs.getCount());
                if (lastVisiblePosition == lvfs.getCount() - 2 - 1 && lvfs.getCount() - 2 >= countSize) {
                    pageSize++;
                    initComment(Constants.LOADMORE);
                }
                if (lastVisiblePosition == lvfs.getCount() - 1) {
                    if (!isshow) {
                        inAnim();
                        isshow = true;
                    }
                }
            }
        });

        lvfs.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        y1 = motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        y2 = motionEvent.getY();
                        if (y1 == 0) {
                            y1 = y2;
                        }
                        if ((y1 - y2) > 1 && !(lastVisiblePosition == lvfs.getCount() - 1)) {
//                            ToastUtils.show(context, "向上滑");
                            if (isshow) {
                                isshow = false;
                                outAnim();
                            }
                            y1 = y2;
                        } else if (y1 - y2 < -1) {
//                            ToastUtils.show(context, "向下滑");
                            if (!isshow) {
                                isshow = true;
                                inAnim();
                            }
                            y1 = y2;
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        y1 = 0;
                        break;
                }
                return false;
            }
        });
    }

    @Override
    protected void processLogic() {
//        bgTopBarDrawable = top_bar.getBackground();
//        bgTopBarDrawable.mutate().setAlpha(alpha);
//        top_bar_tv_title.setTextColor(Color.argb(alpha, 255, 255, 255));   //文字透明度
        initComment(Constants.INITDATA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 47:
                parentCommentBean = (CommentBean) data.getSerializableExtra("bean");
                commentBeanList.get(position).setStatus(parentCommentBean.getStatus());
                commentBeanList.get(position).setZan(parentCommentBean.getZan());
                commentBeanList.get(position).setChild_count(parentCommentBean.getChild_count());
                tv_value_num.setText(Integer.valueOf(tv_value_num.getText().toString()) + data.getIntExtra("add_child_count", 0) + "");
                valueAdapter.notifyDataSetChanged();
        }
    }

    private void initPopupWindow() {
        layout = LayoutInflater.from(DetailActivity.this).inflate(
                R.layout.layout_detail_popwindow, null);
        popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setAnimationStyle(R.style.PopAnimation);
        LinearLayout ll_focus = (LinearLayout) layout.findViewById(R.id.ll_focus);
        LinearLayout ll_share = (LinearLayout) layout.findViewById(R.id.ll_share);
        ll_focus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.show(context, "关注");
                popupWindow.dismiss();
            }
        });
        ll_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.show(context, "分享");
                popupWindow.dismiss();
            }
        });
    }

    private void initHeader() {
        topView = LayoutInflater.from(context).inflate(R.layout.layout_detail_header, null);
        wv = (WebView) topView.findViewById(R.id.wv);
        WebSettings webSettings = wv.getSettings();
        wv.setWebViewClient(new DetailWebViewClient());
        webSettings.setCacheMode(Constants.WEB_CACHE);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript脚本
//        webSettings.setBuiltInZoomControls(true);// 设置支持缩放
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        wv.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
//        webSettings.setUseWideViewPort(true);// 图片被缩放后显示不全的问题
        //自适应屏幕
        wv.getSettings().setLoadWithOverviewMode(true);
        wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        switch (settingUtils.getZiTiDaXiao()) {
            case 0:
                wv.getSettings().setTextZoom(100);
                break;
            case 1:
                wv.getSettings().setTextZoom(125);
                break;
            case 2:
                wv.getSettings().setTextZoom(150);
                break;
        }
        lvfs.addHeaderView(topView);
        lvfs.addFooterView(LayoutInflater.from(context).inflate(R.layout.layout_detail_footer, null));
        getDetail();
    }

    public class DetailWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            handler.sendEmptyMessageDelayed(0, 0);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_write_value:
                if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
                    startActivity(new Intent(DetailActivity.this, UserLoginActivity2.class));
                } else {
                    showEditDialog();
                }
                break;
            case R.id.rl_value:
                lvfs.setSelection(1);
                break;
            case R.id.ll_focus:
                if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
                    startActivity(new Intent(DetailActivity.this, UserLoginActivity2.class));
                    return;
                }
                setFocus();
                break;
            case R.id.ll_share:
                CommonUtils.showShare(DetailActivity.this, getIntent().getStringExtra("title"), " ", UrlUtils.BASEHTTP + articleDetailBean.getData().getUrl());
                break;
        }
    }


    /**
     * 发送消息
     */
    private void showEditDialog() {
        if (alertDialog == null) {
            alertDialog = new AlertDialog.Builder(DetailActivity.this, R.style.Translucent_NoTitle).create();
            View editView = getLayoutInflater().inflate(R.layout.ui_edit_comment, null);
            alertDialog.setView(editView);
            dialog_et_content = (EditText) editView.findViewById(R.id.send_commnet_ed_content);
            btn_submit = (TextView) editView.findViewById(R.id.btn_submit);
            alertDialog.show();
            Window win = alertDialog.getWindow();
            win.getDecorView().setPadding(0, 0, 0, 0);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.FILL_PARENT; // 设置宽度
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setGravity(Gravity.BOTTOM);
            win.setAttributes(lp);
        } else {
            alertDialog.show();
        }
        dialog_et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(dialog_et_content.getText())) {
                    btn_submit.setEnabled(false);
                } else {
                    btn_submit.setEnabled(true);
                }
            }
        });
        final Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                InputMethodManager inputManager =
                        (InputMethodManager) dialog_et_content.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(dialog_et_content, 0);
                timer.cancel();
            }
        };
        timer.schedule(timerTask, 200);

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestParams params = new RequestParams();
                params.put("uid", BaseApp.getModel().getId());
                params.put("content", dialog_et_content.getText().toString());
                params.put("avatar", BaseApp.getModel().getAvatar());
                params.put("nickname", BaseApp.getModel().getNickname());
                params.put("aid", getIntent().getStringExtra("id"));
                dialog_et_content.setText("");
                alertDialog.dismiss();
                RestClient.post(UrlUtils.COMMENT_ADD, params, context, new ResponseListener(DetailActivity.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, JSONObject result) {
                        try {
                            CommentBean commentBeanRefresh = (CommentBean) JSON.parseObject(result.getJSONObject("data").toString(), CommentBean.class);
                            commentBeanRefresh.setChild_count("0");
                            commentBeanList.add(0, commentBeanRefresh);
                            valueAdapter = new ValueAdapter();
                            lvfs.setAdapter(valueAdapter);
//                            valueAdapter.notifyDataSetChanged();
                            lvfs.setSelection(1);
                            tv_value_num.setText(Integer.valueOf(tv_value_num.getText().toString()) + 1 + "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private class ValueAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return commentBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return commentBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(context, R.layout.item_detail_value, null);
                holder.iv_avatar = (ImageView) view.findViewById(R.id.iv_avatar);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.tv_content = (TextView) view.findViewById(R.id.tv_content);
                holder.iv_like = (ImageView) view.findViewById(R.id.iv_like);
                holder.tv_like = (TextView) view.findViewById(R.id.tv_like);
                holder.ll_reply = (LinearLayout) view.findViewById(R.id.ll_reply);
                holder.lvfs_reply = (ListViewForScrollView) view.findViewById(R.id.lvfs_reply);
                holder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                holder.tv_reply = (TextView) view.findViewById(R.id.tv_reply);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            switch (settingUtils.getZiTiDaXiao()) {
                case 0:
                    holder.tv_content.setTextSize(13);
                    break;
                case 1:
                    holder.tv_content.setTextSize(17);
                    break;
                case 2:
                    holder.tv_content.setTextSize(21);
                    break;
            }
            final CommentBean commentBean = commentBeanList.get(i);
            if (!TextUtils.isEmpty(commentBean.getAvatar())) {
                imageLoader.displayImage(commentBeanList.get(i).getAvatar(), holder.iv_avatar, options);
            } else {
                imageLoader.displayImage("", holder.iv_avatar, options);
            }
            if (TextUtils.isEmpty(commentBean.getNickname())) {
                holder.tv_name.setText("游客");
            } else {
                holder.tv_name.setText(commentBean.getNickname());
            }
            if (commentBean.getStatus() == 0) {
                holder.iv_like.setEnabled(true);
                holder.tv_like.setEnabled(true);
            } else {
                holder.iv_like.setEnabled(false);
                holder.tv_like.setEnabled(false);
            }
            holder.tv_like.setText(commentBean.getZan());
            holder.tv_content.setText(commentBean.getContent());
            holder.tv_time.setText(TimeUtils.milliseconds2String(Long.valueOf(commentBean.getAddtime()) * 1000, new SimpleDateFormat("MM-dd HH:mm")) + " " + commentBean.getChild_count() + "条评论>");
//            if (commentBean.getChildren() != null) {
//                if (commentBean.getChildren().size() == 0) {
//                    holder.ll_reply.setVisibility(View.GONE);
//                    holder.tv_reply.setText("查看全部评论");
//                } else {
//                    holder.ll_reply.setVisibility(View.VISIBLE);
//                    holder.tv_reply.setText("查看全部" + commentBean.getChild_count() + "条评论");
//                }
//                ReplyAdapter replyAdapter = new ReplyAdapter(commentBean.getChildren());
//                holder.lvfs_reply.setAdapter(replyAdapter);
//            } else {
//                holder.ll_reply.setVisibility(View.GONE);
//                holder.tv_reply.setText("查看全部评论");
//            }
            view.findViewById(R.id.ll).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
                        startActivity(new Intent(DetailActivity.this, UserLoginActivity2.class));
                        return;
                    }
                    position = commentBeanList.indexOf(commentBean);
                    Intent intent = new Intent(context, ReplyActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("bean", commentBean);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                }
            });
//            holder.lvfs_reply.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                @Override
//                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
//                        startActivity(new Intent(DetailActivity.this, UserLoginActivity2.class));
//                        return;
//                    }
//                    position = commentBeanList.indexOf(commentBean);
//                    Intent intent = new Intent(context, ReplyActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("bean", commentBean);
//                    intent.putExtras(bundle);
//                    startActivityForResult(intent, 1);
//                }
//            });
            holder.iv_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (TextUtils.isEmpty(BaseApp.getModel().getId())) {
                        startActivity(new Intent(DetailActivity.this, UserLoginActivity2.class));
                        return;
                    }
                    RequestParams params = new RequestParams();
                    params.put("uid", BaseApp.getModel().getId());
                    params.put("avatar", BaseApp.getModel().getAvatar());
                    params.put("nicname", BaseApp.getModel().getNickname());
                    params.put("aid", commentBean.getAid());
                    params.put("cid", commentBean.getId());
                    RestClient.post(UrlUtils.DIANZAN, params, context, new ResponseListener(DetailActivity.this, true) {
                        @Override
                        public void success(int arg0, Header[] arg1, JSONObject result) {
                            ToastUtils.show(context, "点赞成功");
                            commentBean.setZan(Integer.valueOf(holder.tv_like.getText().toString()) + 1 + "");
                            commentBean.setStatus(1);
                            notifyDataSetChanged();
                        }
                    });
                }
            });

            holder.tv_like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RequestParams params = new RequestParams();
                    params.put("uid", BaseApp.getModel().getId());
                    params.put("avatar", BaseApp.getModel().getAvatar());
                    params.put("nicname", BaseApp.getModel().getNickname());
                    params.put("aid", commentBean.getAid());
                    params.put("cid", commentBean.getId());
                    RestClient.post(UrlUtils.DIANZAN, params, context, new ResponseListener(DetailActivity.this, true) {
                        @Override
                        public void success(int arg0, Header[] arg1, JSONObject result) {
                            ToastUtils.show(context, "点赞成功");
                            commentBean.setZan(Integer.valueOf(holder.tv_like.getText().toString()) + 1 + "");
                            commentBean.setStatus(1);
                            notifyDataSetChanged();
                        }
                    });
                }
            });
            return view;
        }
    }

    class ViewHolder {
        private ImageView iv_avatar;
        private TextView tv_name;
        private TextView tv_content;
        private ImageView iv_like;
        private TextView tv_like;
        private LinearLayout ll_reply;
        private ListViewForScrollView lvfs_reply;
        private TextView tv_time;
        private TextView tv_reply;
    }

    private class ReplyAdapter extends BaseAdapter {
        private List<CommentBean> commentBeanList;

        public ReplyAdapter(List<CommentBean> commentBeanList) {
            this.commentBeanList = commentBeanList;

        }

        @Override
        public int getCount() {
            return commentBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return commentBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolderReply holder;
            if (view == null) {
                holder = new ViewHolderReply();
                view = View.inflate(context, R.layout.item_reply_reply, null);
                holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
                holder.tv_content = (TextView) view.findViewById(R.id.tv_content);
                view.setTag(holder);
            } else {
                holder = (ViewHolderReply) view.getTag();
            }
            CommentBean commentBean = commentBeanList.get(i);
            if (TextUtils.isEmpty(commentBean.getNickname())) {
                holder.tv_name.setText("游客:");
            } else {
                holder.tv_name.setText(commentBean.getNickname() + ":");
            }
            holder.tv_content.setText(commentBean.getContent());
            return view;
        }
    }

    class ViewHolderReply {
        private TextView tv_name;
        private TextView tv_content;
    }

    private void getDetail() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("uid", BaseApp.getModel().getId());
        httpParams.put("id", getIntent().getStringExtra("id"));
        String cachekey = "detail&uid=" + BaseApp.getModel().getId() + "&id=" + getIntent().getStringExtra("id");
        OkGoRequest.post(UrlUtils.DETAIL, DetailActivity.this, cachekey, CacheMode.REQUEST_FAILED_READ_CACHE, httpParams, new StringCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                rl_progress.setVisibility(View.VISIBLE);
                avi.setVisibility(View.VISIBLE);
                ll_reload.setVisibility(View.GONE);
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onCacheError(Call call, Exception e) {
                super.onCacheError(call, e);
                Message msg = new Message();
                msg.what = 2;
                handler.sendMessageDelayed(msg, Constants.DELAYTIMES);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    articleDetailBean = JSON.parseObject(result.toString(), ArticleDetailBean.class);
//                    wv.loadData(articleDetailBean.getData().getContent(), "text/html; charset=UTF-8", null);//这种写法可以正确解码
                    wv.loadUrl(UrlUtils.BASEHTTP + articleDetailBean.getData().getUrl());
                    if (articleDetailBean.getData().getMark() == 0) {
                        iv_focus.setImageDrawable(getResources().getDrawable(R.mipmap.ic_favourite_normal));
                    } else {
                        iv_focus.setImageDrawable(getResources().getDrawable(R.mipmap.ic_favourite_selected));
                    }
                    if (Integer.valueOf(articleDetailBean.getData().getComment()) > 0) {
                        tv_value_num.setText(articleDetailBean.getData().getComment());
                        tv_value_num.setVisibility(View.VISIBLE);
                    } else {
                        tv_value_num.setVisibility(View.GONE);
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initComment(final int type) {
        boolean isShow = false;
        switch (type) {
            case Constants.INITDATA:
                isShow = false;
                break;
            case Constants.LOADMORE:
                isShow = false;
                break;
            case Constants.REFRESH:
                isShow = true;
                break;
        }
        HttpParams params = new HttpParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("aid", getIntent().getStringExtra("id"));
        params.put("p", pageSize);
        params.put("rows", countSize);
        String url = UrlUtils.COMMENT_LIST + "&uid=" + BaseApp.getModel().getId() + "&aid=" + getIntent().getStringExtra("id") + "&p=" + pageSize + "&rows=" + countSize;
        String cacheKey = "comment_list&uid=" + BaseApp.getModel().getId() + "&aid=" + getIntent().getStringExtra("id") + "&p=" + pageSize + "&rows=" + countSize;
        OkGoRequest.post(url, DetailActivity.this, cacheKey, CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    switch (type) {
                        case Constants.INITDATA:
                            commentBeanList = JSON.parseArray(result.getJSONArray("data").toString(), CommentBean.class);
                            valueAdapter = new ValueAdapter();
                            lvfs.setAdapter(valueAdapter);
//                            valueAdapter.notifyDataSetChanged();
                            break;
                        case Constants.LOADMORE:
                            commentBeanList.addAll(JSON.parseArray(result.getJSONArray("data").toString(), CommentBean.class));
                            valueAdapter.notifyDataSetChanged();
                            break;
                    }
                    lastVisiblePosition = lvfs.getLastVisiblePosition();
                } catch (JSONException e) {
                    e.printStackTrace();
                    if (type == Constants.INITDATA) {
                        lvfs.setAdapter(new TestAdapter(context));
//                        valueAdapter = new ValueAdapter();
//                        lvfs.setAdapter(valueAdapter);
                    }

                }
            }
        });
    }

    private void setFocus() {
        HttpParams params = new HttpParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("id", articleDetailBean.getData().getId());
        if (articleDetailBean.getData().getMark() == 0) {
            params.put("met", "yes");
        } else {
            params.put("met", "no");
        }
        String cacheKey = "bmark&uid=" + BaseApp.getModel().getId() + "id=" + articleDetailBean.getData().getId();
        OkGoRequest.post(UrlUtils.BMARK, DetailActivity.this, cacheKey, CacheMode.NO_CACHE, params, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (articleDetailBean.getData().getMark() == 0) {
                    articleDetailBean.getData().setMark(1);
                    iv_focus.setImageDrawable(getResources().getDrawable(R.mipmap.ic_favourite_selected));
                    ToastUtils.show(context, "收藏成功");
                    setResult(Constants.ADD_FAV, getIntent());
                } else {
                    articleDetailBean.getData().setMark(0);
                    iv_focus.setImageDrawable(getResources().getDrawable(R.mipmap.ic_favourite_normal));
                    ToastUtils.show(context, "取消收藏");
                    setResult(Constants.CANCEL_FAV, getIntent());
                }
            }
        });
    }

    private void outAnim() {
        float curTranslationY = ll_bottom.getTranslationY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_bottom, "translationY", 150f);
        animator.setDuration(500);
        animator.start();
//        ObjectAnimator animator2 = ObjectAnimator.ofFloat(findViewById(R.id.iv_back), "translationY", -150f);
//        animator2.setDuration(500);
//        animator2.start();
    }

    private void inAnim() {
        float curTranslationY = ll_bottom.getTranslationY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_bottom, "translationY", 0f);
        animator.setDuration(500);
        animator.start();
//        ObjectAnimator animator2 = ObjectAnimator.ofFloat(findViewById(R.id.iv_back), "translationY", 0f);
//        animator2.setDuration(500);
//        animator2.start();
    }
}
